﻿using System.Windows;

namespace Niaofei.WPF.Control
{
    /// <summary>
    /// 等待装饰器辅助类
    /// </summary>
    public static class LodingAdornerHelper
    {
        public static readonly DependencyProperty IsLoadingProperty =
            DependencyProperty.RegisterAttached(
                "IsLoading",
                typeof(bool),
                typeof(LodingAdornerHelper),
                new PropertyMetadata(false, OnIsLoadingChanged));

        public static void SetIsLoading(DependencyObject element, bool value)
        {
            element.SetValue(IsLoadingProperty, value);
        }

        public static bool GetIsLoading(DependencyObject element)
        {
            return (bool)element.GetValue(IsLoadingProperty);
        }

        private static readonly DependencyProperty BusyIndicatorInstanceProperty =
            DependencyProperty.RegisterAttached(
                "BusyIndicatorInstance",
                typeof(BusyIndicator),
                typeof(LodingAdornerHelper),
                new PropertyMetadata(null));

        private static void SetBusyIndicatorInstance(DependencyObject element, BusyIndicator? value)
        {
            element.SetValue(BusyIndicatorInstanceProperty, value);
        }

        private static BusyIndicator? GetBusyIndicatorInstance(DependencyObject element)
        {
            return element.GetValue(BusyIndicatorInstanceProperty) as BusyIndicator;
        }

        private static void OnIsLoadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is FrameworkElement fe)
            {
                if (!fe.IsLoaded)
                {
                    RoutedEventHandler? loadedHandler = null;
                    loadedHandler = (s, args) =>
                    {
                        fe.Loaded -= loadedHandler;
                        if (GetIsLoading(fe))
                        {
                            var indicator = GetBusyIndicatorInstance(fe) ?? new BusyIndicator(fe);
                            indicator.Start(null);
                            SetBusyIndicatorInstance(fe, indicator);
                        }
                    };
                    fe.Loaded += loadedHandler;
                    return;
                }

                if ((bool)e.NewValue)
                {
                    var indicator = GetBusyIndicatorInstance(fe) ?? new BusyIndicator(fe);
                    indicator.Start(null);
                    SetBusyIndicatorInstance(fe, indicator);
                }
                else
                {
                    var indicator = GetBusyIndicatorInstance(fe);
                    indicator?.Stop();
                    SetBusyIndicatorInstance(fe, null);
                }
            }
        }
    }
}
